package com.example.wisdomclassroomapi.facade.controller.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wisdomclassroomapi.application.service.AuthUserApplicationService;
import com.example.wisdomclassroomapi.common.dto.PageDto;
import com.example.wisdomclassroomapi.domain.entity.AuthUserEntity;
import com.example.wisdomclassroomapi.facade.assembler.AuthUserFacadeAssembler;
import com.example.wisdomclassroomapi.facade.controller.common.BaseController;
import com.example.wisdomclassroomapi.facade.dto.AuthUserRequestDto;
import com.example.wisdomclassroomapi.facade.dto.AuthUserResponseDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.example.wisdomclassroomapi.facade.controller.wxapp
 * @Description: <前端控制器>-相关接口
 * @Author: scholes
 * @CreateDate: 2022-04-18
 * @UpdateUser: scholes
 * @UpdateDate: 2022-04-18
 * @UpdateRemark: <>
 * @Version: 1.0
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
public class AuthUserController extends BaseController {
    @Resource
    private AuthUserApplicationService authUserApplicationService;

    @Resource
    private AuthUserFacadeAssembler authUserFacadeAssembler;

    @Resource
    private PasswordEncoder passwordEncoder;

    /**
     * 分页查询
     */
    @PostMapping("/page")
    public PageDto<List<AuthUserResponseDto>> getAuthUserByPage(@RequestBody @Valid AuthUserRequestDto request) {
        IPage<AuthUserEntity> page = new Page<AuthUserEntity>();
        page.setSize(request.getPageSize());
        page.setCurrent(request.getPageNum());
        AuthUserEntity entity = authUserFacadeAssembler.assembleAuthUserEntity(request);
        page = authUserApplicationService.page(entity, page);
        List<AuthUserResponseDto> assembleData = new ArrayList<>();
        if (page != null && page.getRecords() != null && page.getRecords().size() > 0) {
            for (AuthUserEntity item : page.getRecords()) {
                assembleData.add(authUserFacadeAssembler.assembleAuthUserResponseDto(item));
            }
        }
        PageDto<List<AuthUserResponseDto>> result = new PageDto<>();
        result.setPageSize((int) page.getSize());
        result.setPageNum((int) page.getCurrent());
        result.setTotal(page.getTotal());
        result.setData(assembleData);
        return result;
    }


    /**
     * 查询
     */
    @PostMapping("/list")
    public List<AuthUserResponseDto> getAuthUsers(@RequestBody @Valid AuthUserRequestDto request) {
        AuthUserEntity entity = authUserFacadeAssembler.assembleAuthUserEntity(request);
        List<AuthUserEntity> list = authUserApplicationService.list(entity);
        List<AuthUserResponseDto> assembleData = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (AuthUserEntity item : list) {
                assembleData.add(authUserFacadeAssembler.assembleAuthUserResponseDto(item));
            }
        }
        return assembleData;
    }

    /**
     * 获取某一实体
     */
    @PostMapping("/getById")
    public AuthUserResponseDto getAuthUserDetails(@RequestBody AuthUserEntity entity) {
        entity = authUserApplicationService.findById(entity.getId());
        AuthUserResponseDto responseDto = null;
        if (entity != null) {
            responseDto = authUserFacadeAssembler.assembleAuthUserResponseDto(entity);
        }
        return responseDto;
    }

    /**
     * 新增数据
     */
    @PostMapping("/add")
    @PreAuthorize("hasRole('leader')")
    public String saveAuthUser(@RequestBody Map<String, String> params) {
        // 添加信息
        String id = authUserApplicationService.add(params);
        // 绑定角色
        authUserApplicationService.bindRole(id, JSON.parseArray(params.get("roleId"), String.class));
        // 绑定班级
        authUserApplicationService.bindClass(id, JSON.parseArray(params.get("classId"), String.class));
        return id;
    }

    /**
     * 修改数据
     */
    @PostMapping("/update")
    @PreAuthorize("hasRole('leader')")
    public void modifyAuthUser(@RequestBody Map<String, String> params) {
        // 信息装载
        AuthUserEntity entity = new AuthUserEntity();
        entity.setId(params.get("id"));
        entity.setUsername(params.get("username"));
        entity.setPassword(params.get("password"));
        entity.setEmail(params.get("email"));
        entity.setMobile(params.get("mobile"));
        entity.setRealName(params.get("realName"));

        // 加密密码
        if (StringUtils.isNotBlank(entity.getPassword())) entity.setPassword(passwordEncoder.encode(entity.getPassword()));

        // 更新信息
        authUserApplicationService.updateById(entity);
        // 绑定角色
        List<String> roleId = JSON.parseArray(params.get("roleId"), String.class);
        if (roleId != null && !roleId.isEmpty()) authUserApplicationService.bindRole(entity.getId(), roleId);
        // 绑定班级
        List<String> classId = JSON.parseArray(params.get("classId"), String.class);
        if (classId != null && !classId.isEmpty()) authUserApplicationService.bindClass(entity.getId(), classId);
    }

    /**
     * 删除数据
     */
    @PostMapping("/delete")
    @PreAuthorize("hasRole('leader')")
    public void removeAuthUser(@RequestBody Map<String, String> params) {
        authUserApplicationService.deleteById(params.get("id"));
    }
}